package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.bugtags.library.Bugtags;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerProblemBack;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * Created by Lenovo on 2017/3/1.
 */
public class CustomerProblemBackDetailFragment extends Fragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.CustomerProblemBackDetailFragment.EXTRA_CONTENT";
  private static final int NEW = 0;
  private static final int SUBMIT = 1;
  private static final int PUBLISH = 2;

  private static final int PROBLEM_TYPE = 3;
  private static final int DEVICE_TYPE = 4;
  private static final int SERVICE_TYPE = 5;
  private static final int ADDFILE = 6;
  private static final int ADD = 7;
  private static final int REQUEST_UPLOAD = 8;

  @BindView(R.id.tv_problemType) TextView tvProblemType;
  @BindView(R.id.tv_deviceType) TextView tvDeviceType;
  @BindView(R.id.et_funidCode) EditText etFunidCode;
  @BindView(R.id.ll_deviceType) LinearLayout llDeviceType;
  //@BindView(R.id.tv_serviceUnit) TextView tvServiceUnit;
  //@BindView(R.id.ll_serviceUnit)
  //LinearLayout llServiceUnit;
  @BindView(R.id.et_problemDetails) EditText etProblemDetails;
  @BindView(R.id.et_remark) EditText etRemark;
  @BindView(R.id.tv_file) TextView tvFile;
  @BindView(R.id.iv_file) ImageView ivFile;
  @BindView(R.id.tv_titleRight) TextView tvDataStatus;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_submitTime) TextView tvRegDate;

  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private int menuType;
  private CustomerProblemBack mContent;
  private String mFilePath;
  private String mId;
  private String problemTypeCode;
  //private String serviceUnitCode;

  public static CustomerProblemBackDetailFragment newInstance(CustomerProblemBack content) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    CustomerProblemBackDetailFragment fragment = new CustomerProblemBackDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.back_detail);
      actionBar.setDisplayHomeAsUpEnabled(true);
    }
    mUser = CurrentUser.newInstance(getActivity());
    mContent = (CustomerProblemBack) getArguments().getSerializable(EXTRA_CONTENT);
    if (mContent == null) {
      mId = UUID.randomUUID().toString();
      problemTypeCode = "";
      //serviceUnitCode = "";
      mFilePath = "";
      //添加
      menuType = ADD;
    }
    if (mContent != null) {
      //详情
      mId = mContent.getId();
      problemTypeCode = mContent.getProblemType();
      //serviceUnitCode = mContent.getServiceUnitCode();
      mFilePath = mContent.getFilepath1();
      if (DataStatus.NEW.equalsIgnoreCase(mContent.getDataStatus())) {
        menuType = NEW;
      } else if (DataStatus.SUBMIT.equalsIgnoreCase(mContent.getDataStatus())) {
        menuType = SUBMIT;
      } else {
        menuType = PUBLISH;
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (menuType) {
      //草稿状态：保存、保存并提交
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //草稿状态：保存、启动流程、删除
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //提交状态：终止
      case SUBMIT:
        //                inflater.inflate(R.menu.menu_stop, menu);
        break;
      //已完成状态：
      case PUBLISH:
        break;
      default:
        break;
    }

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      //保存
      case R.id.menu_item_save:
        if (isComplete()) {
          volleyPostSave(false);
        }
        return true;

      //保存并提交
      case R.id.menu_item_submit:
        if (isComplete()) {
          //volleyPostSubmit();
          volleyPostSave(true);
        }
        return true;

      //删除
      case R.id.menu_item_delete:
        volleyPostDelete();
        return true;

      //终止流程
      case R.id.menu_item_stop:
        volleyPostStop();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private boolean isComplete() {
    if (TextUtils.isEmpty(tvProblemType.getText().toString())) {
      ToastUtil.show(R.string.problemTypeHint);
      return false;
    }
    if (TextUtils.isEmpty(etProblemDetails.getText().toString())) {
      ToastUtil.show(R.string.toastMessage);
      return false;
    }
    return true;
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_problem_detail, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    if (mContent != null) {
      if ("S".equalsIgnoreCase(mContent.getProblemType())) {
        tvProblemType.setText(R.string.deviceProblem);
        tvDeviceType.setText(mContent.getDeviceType());
        etFunidCode.setText(mContent.getFunidCode());
        //                llServiceUnit.setVisibility(View.GONE);
      } else if ("F".equalsIgnoreCase(mContent.getProblemType())) {
        tvProblemType.setText(R.string.serviceProblem);
        llDeviceType.setVisibility(View.GONE);
      } else if ("Z".equalsIgnoreCase(mContent.getProblemType())) {
        tvProblemType.setText(R.string.suggest);
        //                llServiceUnit.setVisibility(View.GONE);
        llDeviceType.setVisibility(View.GONE);
      } else {
        tvProblemType.setText("");
        //                llServiceUnit.setVisibility(View.GONE);
        llDeviceType.setVisibility(View.GONE);
      }
      //tvServiceUnit.setText(mContent.getServiceUnitName());
      etProblemDetails.setText(mContent.getProblemDetails());
      etRemark.setText(mContent.getRemark());
      tvFile.setText(mContent.getFileOriginalName());
      tvDataStatus.setText(mContent.getDataStatusName());
      tvRegStaffName.setText(mContent.getRegStaffName());
      //noinspection deprecation
      tvRegDate.setText(
          MyDateUtil.parseDateToString(MyDateUtil.stringToDate(mContent.getRegDate())));
      if (DataStatus.SUBMIT.equalsIgnoreCase(mContent.getDataStatus())
          || DataStatus.REPLAY.equalsIgnoreCase(mContent.getDataStatus())) {
        //已提交，已回复不能编辑
        tvProblemType.setEnabled(false);
        tvDeviceType.setEnabled(false);
        etProblemDetails.setEnabled(false);
        tvDeviceType.setEnabled(false);
        etFunidCode.setEnabled(false);
        //tvServiceUnit.setEnabled(false);
        etRemark.setEnabled(false);
        ivFile.setVisibility(View.GONE);
      }
    }
    if (mContent == null) {
      tvDataStatus.setText(R.string.draft);
      tvRegStaffName.setText(mUser.getRealName());
      //noinspection deprecation
      tvRegDate.setText(MyDateUtil.parseDateToString(new Date()));
      //            llServiceUnit.setVisibility(View.GONE);
      llDeviceType.setVisibility(View.GONE);
    }
  }

  @OnClick({
      R.id.tv_problemType, R.id.tv_deviceType, R.id.tv_file, R.id.iv_file
  }) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_problemType:
        showDialog(PROBLEM_TYPE);
        break;
      case R.id.tv_deviceType:
        showDialog(DEVICE_TYPE);
        break;
      //case R.id.tv_serviceUnit:
      //  showDialog(SERVICE_TYPE);
      //  break;
      case R.id.tv_file:
        if (mContent != null) {
          downFile(mContent.getFilepath1());
        }
        break;
      case R.id.iv_file:
        chooseFile(ADDFILE);
        break;
    }
  }

  private void downFile(String serverPath) {
    if (!TextUtils.isEmpty(serverPath)) {
      ExtraDownLoadDialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", serverPath);
      FragmentManager fm = getActivity().getSupportFragmentManager();
      dialog.show(fm, "");
    }
  }

  //private String getFile(Intent data) {
  //    String path1 = FileUtil.getPath(getActivity(), data.getData());
  //    File mFile = null;
  //    if (path1 != null) {
  //        mFile = new File(path1);
  //    }
  //    if (null == mFile) {
  //        Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
  //        return "";
  //    }
  //    return mFile.getAbsolutePath();
  //}

  private void chooseFile(int requestCode) {

    /**     Intent intent = new Intent(Intent.ACTION_PICK, null);
     intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
     startActivityForResult(intent, REQUEST_ALBUM);*/
    Intent intent2 = new Intent(Intent.ACTION_PICK, null);
    intent2.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case PROBLEM_TYPE:
        dialog = new ProblemTypeDialogFragment();
        break;
      case DEVICE_TYPE:
        dialog = EquipmentChooseDialogFragment.newInstance("100062");//固定值
        break;
      case SERVICE_TYPE:
        dialog = new SysOrgDialogFragment();
        break;
      default:
        break;
    }
    FragmentManager fm = getFragmentManager();
    assert dialog != null;
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  //取消提交
  private void volleyPostStop() {
    String delUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    params.put("runId", mContent.getId());
    MyUtils.showDialogLoading(getActivity(), R.string.interrupting);
    mActivity.volleyPost(delUrl, params, getResponse(false));
  }

  //删除
  private void volleyPostDelete() {
    String delUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_PROBLEM_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(delUrl, params, getResponse(false));
  }

  //提交
  private void volleyPostSubmit() {
    String startUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_PROBLEM_SUBMIT);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    mActivity.volleyPost(startUrl, params, getResponse(false));
  }

  //保存
  private void volleyPostSave(boolean isSaveAndSubmit) {
    String saveUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_PROBLEM_SAVE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("problemDetails", etProblemDetails.getText().toString());
    params.put("problemType", problemTypeCode);
    params.put("filepath1", mFilePath);
    params.put("remark", etRemark.getText().toString());
    params.put("deviceType", tvDeviceType.getText().toString());
    params.put("funidCode", etFunidCode.getText().toString());
    //params.put("serviceUnitName", tvServiceUnit.getText().toString());
    //params.put("serviceUnitCode", serviceUnitCode);
    CurrentUser user = CurrentUser.newInstance(mActivity);
    Bugtags.sendFeedback(
        MyStringUtil.connect(user.getName(), getString(R.string.comma), user.getPassword(),
            params.toString()));
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    mActivity.volleyPost(saveUrl, params, getResponse(isSaveAndSubmit));
  }

  private VolleyResponse getResponse(final boolean isSaveAndSubmit) {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          //解析
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(result.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {

            if (isSaveAndSubmit) {
              volleyPostSubmit();
            } else {
              ToastUtil.show(R.string.success_operation);
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == PROBLEM_TYPE) {
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(ProblemTypeDialogFragment.EXTRA_TYPE);
      problemTypeCode = content.getId();
      String problemTypeName = content.getName();
      tvProblemType.setText(problemTypeName);
      if ("S".equalsIgnoreCase(problemTypeCode)) {
        llDeviceType.setVisibility(View.VISIBLE);
        //                llServiceUnit.setVisibility(View.GONE);
      } else if ("F".equalsIgnoreCase(problemTypeCode)) {
        llDeviceType.setVisibility(View.GONE);
        //                llServiceUnit.setVisibility(View.VISIBLE);
      } else if ("Z".equalsIgnoreCase(problemTypeCode)) {
        llDeviceType.setVisibility(View.GONE);
        //                llServiceUnit.setVisibility(View.GONE);
      }
    }
    if (requestCode == DEVICE_TYPE) {
      CustomerDialog result =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      tvDeviceType.setText(result.getName());
      //            serviceUnitCode = "";
    }
    //if (requestCode == SERVICE_TYPE) {
    //  CustomerDialog result =
    //      (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
    //  //serviceUnitCode = result.getId();
    //  //tvServiceUnit.setText(result.getName());
    //}
    if (requestCode == ADDFILE) {
      FileUploadDialgFragment dialog = FileUploadDialgFragment.newInstance(getFile(data), mId,
          "imsifwj.wj_erp_o_enterpriseforum_main", true);
      dialog.setTargetFragment(this, REQUEST_UPLOAD);
      dialog.show(mActivity.getSupportFragmentManager(), "");
    }
    if (requestCode == REQUEST_UPLOAD) {
      mFilePath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      tvFile.setText(FileUtil.getFileNameByFilePath(mFilePath));
      if (mContent != null) mContent.setFilepath1(mFilePath);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }
}
